import sys
import requests
from PyQt5.QtWidgets import (
    QApplication,
    QLineEdit,
    QLabel,
    QPushButton,
    QVBoxLayout,
    QWidget,
    QMessageBox
)

from potxui import MyWindow


class CardLoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("卡密登录界面")
        self.resize(300, 150)
        self.server_url = "http://127.0.0.1:5000/api/use"
        self.init_ui()

    def init_ui(self):
        self.card_label = QLabel("请输入卡密:")
        self.card_input = QLineEdit()
        self.card_input.setPlaceholderText("卡密")

        self.login_button = QPushButton("登录")
        self.login_button.clicked.connect(self.handle_login)

        layout = QVBoxLayout()
        layout.addWidget(self.card_label)
        layout.addWidget(self.card_input)
        layout.addWidget(self.login_button)
        self.setLayout(layout)

    def handle_login(self):
        card_key = self.card_input.text().strip()
        if not card_key:
            QMessageBox.warning(self, "输入错误", "卡密不能为空！")
            return
        try:
            response = requests.post(
                self.server_url,
                json={"card_key": card_key},
                timeout=5
            )
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException:
            QMessageBox.critical(self, "网络异常", "网络异常，请检查网络后重试！")
            return
        except ValueError:
            QMessageBox.critical(self, "响应错误", "服务器返回的数据无法解析！")
            return

        success = data.get("success", False)
        message = data.get("message", "未知错误")
        if success:
            QMessageBox.information(self, "登录成功", message)
            self.launch_other_app(card_key)
            self.close()
        else:
            QMessageBox.critical(self, "登录失败", message)

    def launch_other_app(self, card_key):
        if MyWindow is None:
            QMessageBox.warning(self, "启动失败", "未能导入其他应用，请检查模块路径。")
            return
        self.my_windows = MyWindow(card_key)
        self.my_windows.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CardLoginWindow()
    window.show()
    sys.exit(app.exec_())
